package sys

import (
	"ginweb-admin/global"
	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/model"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"go.uber.org/zap"
	"strings"
	"sync"
)

type CasBinService struct{}

// 持久化到数据库  引入自定义规则
var (
	syncedCachedEnforcer *casbin.SyncedCachedEnforcer
	once                 sync.Once
)

// 配置文件的方法
func (service *CasBinService) CasBinFile() *casbin.SyncedCachedEnforcer {
	once.Do(func() {
		a, err := gormadapter.NewAdapterByDB(global.DB)
		if err != nil {
			global.Log.Error("适配数据库失败请检查casbin表是否为InnoDB引擎!", zap.Error(err))
			return
		}
		m, err := model.NewModelFromFile("./conf/rbac_models.conf")
		if err != nil {
			global.Log.Error("字符串加载模型失败!", zap.Error(err))
			return
		}
		syncedCachedEnforcer, _ = casbin.NewSyncedCachedEnforcer(m, a)
		syncedCachedEnforcer.SetExpireTime(60 * 60)
		_ = syncedCachedEnforcer.LoadPolicy()

		// 设置用户root的角色为superadmin
		syncedCachedEnforcer.AddRoleForUser("root", "superadmin")
		// 添加自定义函数
		syncedCachedEnforcer.AddFunction("checkSuperAdmin", func(arguments ...interface{}) (interface{}, error) {
			// 获取用户名
			username := arguments[0].(string)
			// 检查用户名的角色是否为superadmin
			return syncedCachedEnforcer.HasRoleForUser(username, "superadmin")
		})

		// 添加自定义函数
		// equals(r.sub, p.sub)
		syncedCachedEnforcer.AddFunction("equals", func(arguments ...interface{}) (interface{}, error) {
			// 获取用户名
			args1 := arguments[0].(string)
			args2 := arguments[1].(string)
			// 检查用户名的角色是否为superadmin
			return strings.EqualFold(args1, args2), nil
		})

	})
	return syncedCachedEnforcer
}

func (service *CasBinService) Casbin() *casbin.SyncedCachedEnforcer {
	once.Do(func() {
		a, err := gormadapter.NewAdapterByDB(global.DB)
		if err != nil {
			global.Log.Error("适配数据库失败请检查casbin表是否为InnoDB引擎!", zap.Error(err))
			return
		}
		text := `
		[request_definition]
		r = sub, obj, act
		
		[policy_definition]
		p = sub, obj, act
		
		[role_definition]
		g = _, _
		
		[policy_effect]
		e = some(where (p.eft == allow))
		
		[matchers]
		m = r.sub == p.sub && keyMatch2(r.obj,p.obj) && r.act == p.act
		`
		m, err := model.NewModelFromString(text)
		if err != nil {
			global.Log.Error("字符串加载模型失败!", zap.Error(err))
			return
		}
		syncedCachedEnforcer, _ = casbin.NewSyncedCachedEnforcer(m, a)
		syncedCachedEnforcer.SetExpireTime(60 * 60)
		_ = syncedCachedEnforcer.LoadPolicy()
	})
	return syncedCachedEnforcer
}
